package maintain

import (
	"fmt"
	"iot-base/common/webapi"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"

	"iot-base/common/config"

	"iot-base/common/logger"

	"github.com/gin-gonic/gin"
)

type svrAddr struct {
	Addr string `json:"ip"`
	Port int    `json:"port"`
}

func initTunnelAPI(r *gin.RouterGroup) {

	r.POST("/maintain/tunnel", func(c *gin.Context) {
		var addr svrAddr
		err := c.ShouldBind(&addr)
		if err != nil {
			webapi.SendError(err.Error(), webapi.ParamMissed, c)
			return
		}
		sysType := runtime.GOOS
		dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
		cmdName := "etunnel"
		var cmd *exec.Cmd
		params := "-ip " + addr.Addr + " -port " + strconv.Itoa(addr.Port) + " -id " + config.SelfOption.ID
		if sysType == "windows" {
			// windows系统
			killc := exec.Command("cmd", "/C", "taskkill -f -im etunnel")
			killc.Run()

			cmdName = cmdName + ".exe"
			cmdName = dir + "\\" + cmdName
			cmd = exec.Command("cmd", "/C", "start "+cmdName+" "+params)
		} else {
			killc := exec.Command("sh", "-c", "killall etunnel")
			killc.Run()
			cmdName = dir + "/" + cmdName
			cmd = exec.Command("sh", "-c", cmdName+" "+params+" &")
		}

		err = cmd.Start()
		logger.SLog.Info("---------begin cmd", cmdName, err, params)
		fmt.Println("---------begin cmd", cmdName, err, params)
		if err == nil {
			webapi.SendOK(c)
		} else {
			webapi.SendError(err.Error(), webapi.ExecError, c)
		}

	})

}
